package com.linkoog.devtools.json.toolwindow.dialog;

import com.intellij.json.JsonLanguage;
import com.intellij.lang.Language;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.fileEditor.FileEditor;
import com.intellij.openapi.fileEditor.impl.text.TextEditorProvider;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.ValidationInfo;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiFileFactory;
import com.linkoog.devtools.json.toolwindow.JsonToolWindowManager;
import com.linkoog.devtools.utils.JacksonUtil;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.awt.*;

public class JsonAddDialog extends DialogWrapper {

    private final Project project;
    private JPanel myMainPanel;
    private JPanel jsonPanel;


    private FileEditor jsonBodyEditor;

    public JsonAddDialog(@NotNull Project project) {
        super(project, false);
        this.project = project;
        this.setResizable(false);
        this.setSize(580, 450);
        this.setTitle("Json View");
        initJsonPanel();
        init();
    }

    @Override
    protected @Nullable ValidationInfo doValidate() {
        String json = getStringFromEditor();
        if (StringUtils.isBlank(json)) return new ValidationInfo("json 不能为空",  myMainPanel);

        Object jsonValue = parseJson(json);
        if (jsonValue == null) return new ValidationInfo("错误的json字符串，请检查",  myMainPanel);

        return null;
    }

    private Object parseJson(String json){
        try {
            return JacksonUtil.readTree(json);
        }catch (Exception e){
        }
        return null;
    }

    @Override
    public void doCancelAction() {
        super.doCancelAction();
    }

    @Override
    public void dispose() {
        super.dispose();

    }

    @Override
    public void doOKAction() {
        super.doOKAction();
        ApplicationManager.getApplication().invokeLater(() -> {
            String json = getStringFromEditor();
            final JsonToolWindowManager jsonToolWindowManager = project.getService(JsonToolWindowManager.class);
            jsonToolWindowManager.show(json);
        });
    }


    /**
     * set content for editor
     */
    private void setEditorDoc(String text) {
        WriteCommandAction.runWriteCommandAction(project, () -> {
            Document doc = getDocumentFromEditor(jsonBodyEditor);
            doc.deleteString(0, doc.getTextLength());
            doc.setText(text == null ? "" : text.replaceAll("\\r", ""));
        });
    }

    private String getStringFromEditor() {
        Document doc = getDocumentFromEditor(jsonBodyEditor);
        return doc.getText();
    }

    private Document getDocumentFromEditor(FileEditor editor) {
        return FileDocumentManager.getInstance().getCachedDocument(editor.getFile());
    }

    private void initJsonPanel() {
        jsonBodyEditor = createEditor(JsonLanguage.INSTANCE.getID(), null);
        jsonPanel.add(jsonBodyEditor.getComponent(), BorderLayout.CENTER);
    }

    /**
     * create editor with specified language and content
     */
    private FileEditor createEditor(String languageId, String text) {
        if (StringUtils.isEmpty(text)) {
            text = "";
        }

        Language language = Language.findLanguageByID(languageId);
        PsiFile psiFile = PsiFileFactory.getInstance(project).createFileFromText(language, text);
        FileEditor editor = TextEditorProvider.getInstance().createEditor(project, psiFile.getVirtualFile());
        return editor;
    }

    public JPanel getMyMainPanel() {
        return myMainPanel;
    }

    @Override
    protected @Nullable JComponent createCenterPanel() {
        return myMainPanel;
    }
}
